package session_auth

import (
	"encoding/json"
	"fmt"
	"gitee.com/enzolwb/my-web-scaffold/api"
	"gitee.com/enzolwb/my-web-scaffold/pkg/app"
	e "gitee.com/enzolwb/my-web-scaffold/pkg/const"
	"gitee.com/enzolwb/my-web-scaffold/pkg/ecode"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

func SA() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		//验证是否登录Session
		useInfo, ok := session.Get(e.SESSION_USER_INFO_KEY).(string)
		if !ok || useInfo == "" {
			app.Response(c, ecode.ErrForbidden, errors.New("user not login"))
			c.Abort()
			return
		}
		//存下Session结构体信息 省的来回获取
		sessionInfo := &api.SessUserInfo{}
		if err := json.Unmarshal([]byte(fmt.Sprint(useInfo)), sessionInfo); err != nil {
			app.Response(c, ecode.ErrServer)
			c.Abort()
			return
		}
		c.Set(e.CTX_USERSESSION_KEY, sessionInfo)
		c.Next()
	}
}
